<!--公司信息-->
<template>
    <div class="content company-page">
        <section class="base-info">
            <div class="header">
                <h3>基本信息</h3>
            </div>
            <Form :model="companyForm" ref="companyRef" label-position="right" :rules="rules" :label-width="130" inline>
                <Row>
                    <Col span="8">
                    <FormItem label="公司ID：">
                        <Input :value="companyForm.companyId" disabled />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="公司名称：" prop="companyName" class="companyName">
                        <Input
                            v-model.trim="companyForm.companyName"
                            @on-enter="setAssignFocus( 'socialCreditCode')"
                        />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="统一社会信用代码：" prop="socialCreditCode" class="socialCreditCode">
                        <Input :maxlength="18" v-model="companyForm.socialCreditCode" @keyup.native="setAssignFocus('copCode')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="组织机构代码：" prop="copCode" class="copCode">
                        <Input v-model="companyForm.copCode" @keyup.native="setAssignFocus('customsCode')" :maxlength="20" />
                    </FormItem>
                    </Col>

                    <Col span="8">
                    <FormItem label="企业海关代码：" prop="customsCode" class="customsCode">
                        <Input v-model="companyForm.customsCode" :maxlength="10" @keyup.native="setAssignFocus('ciqCode')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="检验检疫编码：" prop="ciqCode" class="ciqCode">
                        <Input v-model="companyForm.ciqCode" :maxlength="10" @keyup.native="setAssignFocus('addressCn')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="公司地址：" prop="addressCn" class="addressCn">
                        <Input v-model="companyForm.addressCn" @keyup.native="setAssignFocus('companyNameEn')" />
                    </FormItem>
                    </Col>

                    <Col span="8">
                    <FormItem label="公司英文名称：" prop="companyNameEn" class="companyNameEn">
                        <Input v-model="companyForm.companyNameEn" @keyup.native="setAssignFocus('addressEn')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="公司英文地址：" prop="addressEn" class="addressEn">
                        <Input v-model="companyForm.addressEn" @keyup.native="setAssignFocus('phone')" />
                    </FormItem>
                    </Col>

                    <Col span="8">
                    <FormItem label="电话号码：" prop="phone" class="phone">
                        <Input v-model="companyForm.phone" @keyup.native="setAssignFocus('fax')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="传真：" prop="fax" class="fax">
                        <Input v-model="companyForm.fax" @keyup.native="setAssignFocus('email')" />
                    </FormItem>
                    </Col>
                    <Col span="8">
                    <FormItem label="电子邮箱：" prop="email" class="email">
                        <Input v-model="companyForm.email" />
                    </FormItem>
                    </Col>
                </Row>
            </Form>
        </section>

        <section>
            <h3>申报单位</h3>
            <div class="data-box">
                <div class="new-btn">
                    <Button type="primary" @click="newAgent">新增</Button>
                </div>
                <table class="data-table" cellpadding="0" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th width="10%">序号</th>
                            <th width="15%">申报单位名称</th>
                            <th width="10%">申报单位海关代码</th>
                            <th width="15%">统一社会信用代码</th>
                            <th width="20%">检验检疫代码</th>
                            <th width="15%">电子签章</th>
                            <th width="15%">管理</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in agentList" :key="index" @dblclick="dblclickHandle(item)">
                            <td width="10%">
                                {{ index + 1 }}    <!--序号-->
                            </td>
                            <td width="15%">
                                <span v-if="!item.isEdit">{{ item.unitName }}</span>       <!--申报单位名称-->
                                <Input
                                    v-else
                                    v-model="item.unitName"
                                    class="td-agentName"
                                    :maxlength="60"
                                    @keyup.native="setAssignFocus('td-customsCode')"
                                >
                                </Input>
                            </td>
                            <td width="10%">
                                <span v-if="!item.isEdit">{{ item.customsCode }}</span>    <!--申报单位海关代码-->
                                <Input
                                    v-else
                                    v-model="item.customsCode"
                                    class="td-customsCode"
                                    :maxlength="10"
                                    @keyup.native="setAssignFocus('td-socialCreditCode')"
                                />
                            </td>
                            <td width="15%">
                                <span v-if="!item.isEdit">{{ item.socialCreditCode }}</span>  <!--统一社会信用代码-->
                                <Input
                                    v-else
                                    v-model="item.socialCreditCode"
                                    class="td-socialCreditCode"
                                    :maxlength="18"
                                    @keyup.native="setAssignFocus('td-ciqCode')"
                                />
                            </td>
                            <td width="20%">
                                <span v-if="!item.isEdit">{{ item.ciqCode }}</span>  <!--检验检疫代码-->
                                <Input :maxlength="10" v-else v-model="item.ciqCode" class="td-ciqCode" />
                            </td>
                            <td width="15%" class="upload-box">
                                <i
                                    :class="['table-icon', item.signatures ? 't-view-icon' : 't-upload-icon'] "
                                    :title="item.signatures ? '查看' : '上传'"
                                    @click="qzImageHandle(item, index)"
                                >
                                </i>
                            </td>
                            <td width="15%">
                                <p v-if="item.isEdit">
                                    <i class="table-icon t-save-icon" title="保存" @click="saveAgent(item)"></i>
                                    <i class="table-icon t-cancel-icon" title="取消" @click="cancelAgent"></i>
                                </p>
                                <p v-else>
                                    <i class="table-icon t-edit-icon" title="编辑" @click="editAgent(item)"></i>
                                    <i class="table-icon t-del-icon" title="删除" @click="removeAgent(index, item)"></i>
                                </p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </section>

        <footer>
            <Button type="primary" @click="saveCompanyInfo">
                确定
            </Button>
            <Button @click="cancelHandle">取消</Button>
        </footer>

        <!-- 电子签章 -->
        <SignatureModal
            v-model="imgModal.visible"
            :url="imgModal.url"
            :action="imgModal.action"
            @deleted="deleteSignature"
            @upload="getImage"
            @on-ok="saveQzUrl"
        ></SignatureModal>
    </div>
</template>
<script>
import { validatePhone, validateSocialCreditCode } from '@/libs/validate'
import { queryCompanyInfo, unifySaveCompany } from '@/api/company'
import SignatureModal from '@/view/resource-manage/customer/components/signature-modal'
import $ from 'jquery'

export default {
    name: 'Company',
    components: {
        SignatureModal
    },
    data () {
        return {
            companyForm: {
                companyId: '',
                companyCode: '',
                companyName: '',
                socialCreditCode: '',
                copCode: '',
                customsCode: '',
                ciqCode: '',
                addressCn: '',
                companyNameEn: '',
                addressEn: '',
                phone: '',
                fax: '',
                email: ''
            },
            agentList: [], // 申报单位
            tempSaveList: [], // 临时保存的申报单位
            parentCompanyList: [],
            isSave: null, // 是否保存
            rules: {
                companyCode: [
                    { required: true, message: '请输入公司代码', trigger: 'blur' }
                ],
                companyName: [
                    { required: true, message: '请输入公司名称', trigger: 'blur' }
                ],
                socialCreditCode: [
                    { required: true, message: '统一社会信用代码不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            validateSocialCreditCode(value)
                                ? callback()
                                : callback(new Error('请输入18位大写字母或数字'))
                        },
                        trigger: 'blur'
                    },
                    { type: 'string', min: 18, max: 18, message: '统一社会信用代码长度18个字符', trigger: 'blur' }
                ],
                customsCode: [
                    { required: true, message: '企业海关编码不能为空', trigger: 'blur' },
                    { type: 'string', max: 10, min: 10, message: '企业海关编码长度10个字符', trigger: 'blur' }
                ],
                ciqCode: [
                    // { required: true, message: '检验检疫编码不能为空', trigger: 'blur' },
                    { type: 'string', min: 10, max: 10, message: '检疫检验编码长度10个字符', trigger: 'blur' }
                ],
                copCode: [
                    { type: 'string', max: 20, message: '组织机构代码最大长度20个字符', trigger: 'blur' }
                ],
                addressCn: [
                    { type: 'string', max: 100, message: '公司地址最大长度100个字符', trigger: 'blur' }
                ],
                companyNameEn: [
                    { type: 'string', max: 100, message: '公司英文名称最大长度100个字符', trigger: 'blur' }
                ],
                addressEn: [
                    { type: 'string', max: 100, message: '公司英文地址最大长度100个字符', trigger: 'blur' }
                ],
                fax: [
                    { type: 'string', max: 20, message: '传真最大长度20个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '电话号码不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            validatePhone(value)
                                ? callback()
                                : callback(new Error('电话号码格式有误'))
                        },
                        trigger: 'blur'
                    }
                ],
                email: [
                    // {required: true, message: '电子邮箱不能为空', trigger: 'blur'},
                    {
                        validator: (rule, value, callback) => {
                            if (value === null || value === '' || value === undefined) {
                                callback()
                            } else if (!(/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value))) {
                                callback(new Error('请输入正确的邮箱'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'change'
                    }
                ]
            },
            imgModal: {
                // 电子签章预览弹出层
                visible: false,
                url: '',
                index: '',
                action: ''
            }
        }
    },
    mounted () {
        this.getCompanyInfo()
    },
    methods: {
        // 获得公司信息
        getCompanyInfo () {
            queryCompanyInfo().then(res => {
                const { data, success, msg } = res.data
                if (success) {
                    if (data) {
                        this.agentList = data.unitList || []
                        data.unitList = null
                        this.companyForm = data
                    }
                } else {
                    this.$Message.warning(msg)
                }
            })
        },

        // 新建申报单位
        newAgent () {
            let isHasEdit = this.agentList.some(item => item.isEdit)
            if (isHasEdit) {
                this.$Message.warning({
                    content: '请先保存正在编辑的申报单位数据!',
                    duration: 3
                })
            } else {
                let tempObj = {
                    companyId: this.companyForm.companyId,
                    unitId: '',
                    unitName: '',
                    customsCode: '',
                    socialCreditCode: '',
                    ciqCode: '',
                    signatures: '',
                    isEdit: true
                }
                this.agentList.push(tempObj)
            }

            this.$nextTick(() => {
                $('.data-table .td-agentName').last().find('.ivu-input').focus()
            })
        },

        dblclickHandle (item) {
            if (!item.isEdit) {
                item.isEdit = true
            }
        },

        // 编辑申报单位
        editAgent (item) {
            let isHasEdit = false
            this.agentList.forEach(item => {
                if (item.isEdit) {
                    isHasEdit = true
                }
            })
            if (isHasEdit) {
                this.$Message.warning({
                    content: '请先保存正在编辑的申报单位数据!',
                    duration: 3
                })
            } else {
                item.isEdit = true
            }
            this.$nextTick(() => {
                $('.data-table .td-agentName').last().find('.ivu-input').focus()
            })
        },

        // 删除申报单位
        removeAgent (index, data) {
            this.agentList.splice(index, 1)
        },

        // 保存申报单位
        saveAgent (item) {
            let reg = /^[0-9A-Z\d]+$/

            if (item.unitName.length > 60) {
                this.$Message.warning({
                    content: '申报单位名称长度不大于60个字符！',
                    duration: 3
                })
                return false
            }

            if (!reg.test(item.customsCode)) {
                this.$Message.warning({
                    content: '申报单位海关代码只能由大写英文字母或数字组成！',
                    duration: 3
                })
                return false
            }

            if (item.customsCode.length !== 10) {
                this.$Message.warning({
                    content: '申报单位海关代码长度为10位！',
                    duration: 3
                })
                return false
            }

            if (!reg.test(item.socialCreditCode)) {
                this.$Message.warning({
                    content: '统一社会信用代码只能由大写英文字母或数字组成！',
                    duration: 3
                })
                return false
            }

            if (item.socialCreditCode.length !== 18) {
                this.$Message.warning({
                    content: '统一社会信用代码长度为18位！',
                    duration: 3
                })
                return false
            }

            item.isEdit = false
            this.tempSaveList = JSON.parse(JSON.stringify(this.agentList))
        },

        // 取消申报单位
        cancelAgent () {
            this.agentList = JSON.parse(JSON.stringify(this.tempSaveList))
        },

        cancelHandle () {
            this.removeCompany()
        },

        removeCompany () {
            this.$router.go(-1)
        },

        qzImageHandle (data, index) {
            this.imgModal.url = data.signatures || ''
            this.imgModal.action = this.$config.uploadUrl
            this.imgModal.index = index
            this.imgModal.visible = true
        },

        getImage (url) {
            this.imgModal.url = url
        },
        saveQzUrl () {
            const index = this.imgModal.index
            this.$set(this.agentList[index], 'signatures', this.imgModal.url)
        },
        deleteSignature () {
            this.imgModal.url = ''
        },
        saveCompanyInfo () {
            this.$refs['companyRef'].validate((valid) => {
                if (valid) {
                    let isHasEdit = this.agentList.some(item => item.isEdit)
                    if (isHasEdit) {
                        this.$Message.warning({
                            content: '请先保存正在编辑的申报单位数据!',
                            duration: 3
                        })
                    } else {
                        let tempArr = JSON.parse(JSON.stringify(this.agentList))
                        tempArr.forEach(item => {
                            delete item.isEdit
                        })
                        const formData = this.companyForm
                        unifySaveCompany({
                            ...formData,
                            list: tempArr
                        }).then(res => {
                            if (res.data.success) {
                                this.$Message.success('保存成功！')
                            } else {
                                this.$Message.error(res.data.msg || '保存失败')
                            }
                        })
                    }
                }
            })
        },

        // 设置指定的元素获得焦点
        setAssignFocus (className) {
            let event = window.event || arguments[0]
            if (event.keyCode === 13) {
                let ele = document.getElementsByClassName(className)[0]
                let t = $(ele).find('.ivu-select-input')

                if (t.length) {
                    t.focus()
                } else {
                    $(ele).find('.ivu-input').focus()
                }
            }
        }
    }
}
</script>

<style lang="less">
    @import "./company";
</style>
